package com.flxz.user.service.impl;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.flxz.common.utils.DateUtils;
import com.flxz.common.utils.SecurityUtils;
import com.flxz.user.mapper.UserTipsMapper;
import com.flxz.user.service.IUserTipsService;
import com.flxz.user.domain.vo.TipsListVO;
import com.flxz.user.domain.vo.TipsDetailVO;
import com.flxz.user.domain.vo.TipsPublishVO;
import com.flxz.user.domain.vo.ReplyVO;
import com.flxz.user.domain.vo.LikeVO;
import com.flxz.user.domain.vo.FavoriteVO;
import com.flxz.user.domain.vo.ReportVO;
import com.flxz.user.domain.vo.CategoryVO;

/**
 * 用户端省薪贴服务实现
 * 
 * @author flxz
 * @date 2025-09-14
 */
@Service
public class UserTipsServiceImpl implements IUserTipsService
{
    @Autowired
    private UserTipsMapper userTipsMapper;

    /**
     * 获取省薪贴列表
     */
    @Override
    public List<TipsListVO> getTipsList(TipsListVO query)
    {
        // 设置默认排序
        if (query.getSortType() == null) {
            query.setSortType("time");
        }
        
        // 设置状态为正常
        query.setStatus("0");
        
        List<TipsListVO> list = userTipsMapper.selectTipsList(query);
        
        // 获取当前用户ID，用于判断点赞和收藏状态
        Long currentUserId = SecurityUtils.getUserId();
        if (currentUserId != null) {
            for (TipsListVO tip : list) {
                // 检查点赞状态
                tip.setIsLiked(userTipsMapper.checkLikeStatus(currentUserId, "1", tip.getTopicId()));
                // 检查收藏状态
                tip.setIsFavorited(userTipsMapper.checkFavoriteStatus(currentUserId, tip.getTopicId()));
            }
        }
        
        return list;
    }

    /**
     * 获取省薪贴详情
     */
    @Override
    public TipsDetailVO getTipsDetail(Long topicId)
    {
        TipsDetailVO detail = userTipsMapper.selectTipsDetail(topicId);
        if (detail == null) {
            return null;
        }
        
        // 获取当前用户ID，用于判断点赞和收藏状态
        Long currentUserId = SecurityUtils.getUserId();
        if (currentUserId != null) {
            detail.setIsLiked(userTipsMapper.checkLikeStatus(currentUserId, "1", topicId));
            detail.setIsFavorited(userTipsMapper.checkFavoriteStatus(currentUserId, topicId));
        }
        
        // 获取回复列表
        ReplyVO replyQuery = new ReplyVO();
        replyQuery.setTopicId(topicId);
        replyQuery.setStatus("0");
        List<ReplyVO> replyList = userTipsMapper.selectReplyList(replyQuery);
        
        // 检查回复的点赞状态
        if (currentUserId != null) {
            for (ReplyVO reply : replyList) {
                reply.setIsLiked(userTipsMapper.checkLikeStatus(currentUserId, "2", reply.getReplyId()));
            }
        }
        
        detail.setReplyList(replyList);
        return detail;
    }

    /**
     * 发布省薪贴
     */
    @Override
    @Transactional
    public int publishTips(TipsPublishVO tipsVO)
    {
        tipsVO.setCreateTime(DateUtils.getNowDate());
        tipsVO.setCreateBy(SecurityUtils.getUsername());
        tipsVO.setStatus("0");
        tipsVO.setTopicType("0");
        tipsVO.setViewCount(0);
        tipsVO.setReplyCount(0);
        tipsVO.setLikeCount(0);
        
        return userTipsMapper.insertTips(tipsVO);
    }

    /**
     * 获取分类列表
     */
    @Override
    public List<CategoryVO> getCategoryList()
    {
        return userTipsMapper.selectCategoryList();
    }

    /**
     * 获取回复列表
     */
    @Override
    public List<ReplyVO> getReplyList(ReplyVO query)
    {
        query.setStatus("0");
        List<ReplyVO> list = userTipsMapper.selectReplyList(query);
        
        // 获取当前用户ID，用于判断点赞状态
        Long currentUserId = SecurityUtils.getUserId();
        if (currentUserId != null) {
            for (ReplyVO reply : list) {
                reply.setIsLiked(userTipsMapper.checkLikeStatus(currentUserId, "2", reply.getReplyId()));
            }
        }
        
        return list;
    }

    /**
     * 发布回复
     */
    @Override
    @Transactional
    public int publishReply(ReplyVO replyVO)
    {
        replyVO.setCreateTime(DateUtils.getNowDate());
        replyVO.setCreateBy(SecurityUtils.getUsername());
        replyVO.setStatus("0");
        replyVO.setReplyType("0");
        replyVO.setLikeCount(0);
        replyVO.setReplyOrder(0);
        
        int result = userTipsMapper.insertReply(replyVO);
        
        // 更新主题的回复次数和最后回复时间
        if (result > 0) {
            userTipsMapper.updateTopicReplyInfo(replyVO.getTopicId(), SecurityUtils.getUserId());
        }
        
        return result;
    }

    /**
     * 点赞/取消点赞
     */
    @Override
    @Transactional
    public int toggleLike(LikeVO likeVO)
    {
        // 检查是否已经点赞
        boolean isLiked = userTipsMapper.checkLikeStatus(likeVO.getUserId(), likeVO.getTargetType(), likeVO.getTargetId());
        
        if (isLiked) {
            // 取消点赞
            userTipsMapper.deleteLike(likeVO.getUserId(), likeVO.getTargetType(), likeVO.getTargetId());
            // 更新点赞数
            userTipsMapper.decreaseLikeCount(likeVO.getTargetType(), likeVO.getTargetId());
        } else {
            // 添加点赞
            likeVO.setCreateTime(DateUtils.getNowDate());
            userTipsMapper.insertLike(likeVO);
            // 更新点赞数
            userTipsMapper.increaseLikeCount(likeVO.getTargetType(), likeVO.getTargetId());
        }
        
        return 1;
    }

    /**
     * 收藏/取消收藏
     */
    @Override
    @Transactional
    public int toggleFavorite(FavoriteVO favoriteVO)
    {
        // 检查是否已经收藏
        boolean isFavorited = userTipsMapper.checkFavoriteStatus(favoriteVO.getUserId(), favoriteVO.getTopicId());
        
        // 根据前端传递的action和实际数据库状态决定操作
        if ("add".equals(favoriteVO.getAction())) {
            // 前端要求添加收藏
            if (!isFavorited) {
                // 数据库中没有收藏记录，添加收藏
                favoriteVO.setCreateTime(DateUtils.getNowDate());
                userTipsMapper.insertFavorite(favoriteVO);
                // 更新收藏数
                userTipsMapper.increaseFavoriteCount(favoriteVO.getTopicId());
            }
            // 如果已经收藏，不做任何操作
        } else if ("remove".equals(favoriteVO.getAction())) {
            // 前端要求取消收藏
            if (isFavorited) {
                // 数据库中有收藏记录，取消收藏
                userTipsMapper.deleteFavorite(favoriteVO.getUserId(), favoriteVO.getTopicId());
                // 更新收藏数
                userTipsMapper.decreaseFavoriteCount(favoriteVO.getTopicId());
            }
            // 如果没有收藏，不做任何操作
        } else {
            // 如果没有指定action，使用自动切换逻辑
            if (isFavorited) {
                // 已经收藏，取消收藏
                userTipsMapper.deleteFavorite(favoriteVO.getUserId(), favoriteVO.getTopicId());
                // 更新收藏数
                userTipsMapper.decreaseFavoriteCount(favoriteVO.getTopicId());
            } else {
                // 未收藏，添加收藏
                favoriteVO.setCreateTime(DateUtils.getNowDate());
                userTipsMapper.insertFavorite(favoriteVO);
                // 更新收藏数
                userTipsMapper.increaseFavoriteCount(favoriteVO.getTopicId());
            }
        }
        
        return 1;
    }

    /**
     * 举报内容
     */
    @Override
    public int reportContent(ReportVO reportVO)
    {
        reportVO.setCreateTime(DateUtils.getNowDate());
        reportVO.setReportStatus("0");
        
        return userTipsMapper.insertReport(reportVO);
    }

    /**
     * 增加浏览次数
     */
    @Override
    public int increaseViewCount(Long topicId)
    {
        return userTipsMapper.increaseViewCount(topicId);
    }

    /**
     * 获取热门省薪贴
     */
    @Override
    public List<TipsListVO> getHotTips()
    {
        TipsListVO query = new TipsListVO();
        query.setStatus("0");
        query.setSortType("hot");
        query.setPageSize(3); // 只取前3个热门
        
        List<TipsListVO> list = userTipsMapper.selectTipsList(query);
        
        // 获取当前用户ID，用于判断点赞和收藏状态
        Long currentUserId = SecurityUtils.getUserId();
        if (currentUserId != null) {
            for (TipsListVO tip : list) {
                tip.setIsLiked(userTipsMapper.checkLikeStatus(currentUserId, "1", tip.getTopicId()));
                tip.setIsFavorited(userTipsMapper.checkFavoriteStatus(currentUserId, tip.getTopicId()));
            }
        }
        
        return list;
    }

    /**
     * 获取我的省薪贴
     */
    @Override
    public List<TipsListVO> getMyTips(TipsListVO query)
    {
        query.setStatus("0");
        List<TipsListVO> list = userTipsMapper.selectMyTips(query);
        
        // 获取当前用户ID，用于判断点赞和收藏状态
        Long currentUserId = SecurityUtils.getUserId();
        if (currentUserId != null) {
            for (TipsListVO tip : list) {
                tip.setIsLiked(userTipsMapper.checkLikeStatus(currentUserId, "1", tip.getTopicId()));
                tip.setIsFavorited(userTipsMapper.checkFavoriteStatus(currentUserId, tip.getTopicId()));
            }
        }
        
        return list;
    }

    /**
     * 获取我的收藏
     */
    @Override
    public List<TipsListVO> getMyFavorites(TipsListVO query)
    {
        query.setStatus("0");
        List<TipsListVO> list = userTipsMapper.selectMyFavorites(query);
        
        // 获取当前用户ID，用于判断点赞和收藏状态
        Long currentUserId = SecurityUtils.getUserId();
        if (currentUserId != null) {
            for (TipsListVO tip : list) {
                tip.setIsLiked(userTipsMapper.checkLikeStatus(currentUserId, "1", tip.getTopicId()));
                tip.setIsFavorited(userTipsMapper.checkFavoriteStatus(currentUserId, tip.getTopicId()));
            }
        }
        
        return list;
    }

    /**
     * 更新我的省薪贴
     */
    @Override
    public int updateMyTips(TipsPublishVO tipsVO)
    {
        tipsVO.setUpdateTime(DateUtils.getNowDate());
        tipsVO.setUpdateBy(SecurityUtils.getUsername());
        
        return userTipsMapper.updateMyTips(tipsVO);
    }

    /**
     * 删除我的省薪贴
     */
    @Override
    @Transactional
    public int deleteMyTips(Long[] topicIds, Long userId)
    {
        // 删除相关的回复
        userTipsMapper.deleteReplyByTopicIds(topicIds);
        // 删除相关的点赞
        userTipsMapper.deleteLikeByTopicIds(topicIds);
        // 删除相关的收藏
        userTipsMapper.deleteFavoriteByTopicIds(topicIds);
        // 删除主题
        return userTipsMapper.deleteMyTips(topicIds, userId);
    }
}
